﻿using System;
using System.Diagnostics;

namespace Unity.Commons.Client.Generator
{
    public static class UnityTimestamp
    {
        private static readonly DateTime DateTimeOnStart = DateTime.UtcNow;
        private static readonly long NanoTimeOnStart = GetCurrentNanoTime();

        private static readonly long ClockOnStart =
        ((DateTimeOffset)DateTimeOnStart).ToUnixTimeSeconds()
        * 1_000_000_000 + NanoTimeOnStart;


        private static long GetCurrentNanoTime()
        {
            long nanoTimeValue = 10_000L * Stopwatch.GetTimestamp();
            nanoTimeValue /= TimeSpan.TicksPerMillisecond;
            nanoTimeValue *= 100L;
            return nanoTimeValue;
        }

        public static long GetNanoTime()
        {
            return ClockOnStart + (GetCurrentNanoTime() - NanoTimeOnStart);
        }

        public static long ClockTimestamp()
        {
            DateTime currentTime = DateTime.UtcNow;
            return ((DateTimeOffset)currentTime).ToUnixTimeSeconds()
                * 1_000_000_000 + GetCurrentNanoTime() / 1000;
        }

        public static long LocalTimeDrift()
        {
            DateTime currentTime = DateTime.UtcNow;
            return ((DateTimeOffset)currentTime).ToUnixTimeSeconds()
                * 1_000_000_000 + GetCurrentNanoTime() - GetNanoTime();
        }
    }
}
